package com.im.business.api.offline.service;

import com.alibaba.fastjson.JSONObject;
import com.im.business.api.offline.JedisManager;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Created leijun
 * @Date 2021/11/3 9:56 下午
 */
@Service
public class OfflineMessageService {

    private Jedis jedis = JedisManager.getJedis();

    /**
     * 查询单聊离线消息
     * @param receiverId
     * @return
     */
    public List<String> selectOfflineSingleMessage(Long receiverId) {
        String key = "offline::single_message::" + receiverId;
        Set<String> messages = jedis.zrevrange(key, 1, -1);
        if (CollectionUtils.isEmpty(messages)) {
            return null;
        }
        return new ArrayList(messages);
    }

    /**
     * 查询群聊离线消息
     * @param groupId
     * @return
     */
    public List<String> selectOfflineGroupMessage(Long groupId) {
        String key = "offline::group_message::" + groupId;
        Set<String> messages = jedis.zrevrange(key, 1, -1);
        if (CollectionUtils.isEmpty(messages)) {
            return null;
        }
        return new ArrayList(messages);
    }

    /**
     * 处理单聊离线消息
     * @param message
     */
    public void handleSingleOfflineMessage(JSONObject message) {
        String receiverId = message.getString("receiverId");
        Long timestamp = message.getLong("timestamp");
        String key = "offline::single_message::" + receiverId;
        jedis.zadd(key, timestamp, message.toJSONString());
    }

    /**
     * 处理群离线消息
     * @param message
     */
    public void handleGroupOfflineMessage(JSONObject message) {
        Long groupId = message.getLong("groupId");
        String receiverId = message.getString("receiverId");
        Long timestamp = message.getLong("timestamp");
        String key = "offline::group_message::" + groupId + ":" + receiverId;
        jedis.zadd(key, timestamp, message.toJSONString());
    }
}
